import * as React from 'react';
import * as _ from 'underscore';
import * as $ from 'jquery';

import {Attachment} from "./attachment";


export interface AttachmentsProps {
    refreshSensitivity?: number;
    refreshThreshold?: number;
    sortable?: boolean;
    resize?: boolean;
    idealColumnWidth?: number;
    attachments: any[];
}


export interface AttachmentsState {

}

export class Attachments extends React.Component<AttachmentsProps, AttachmentsState> {
    public resizeEvent = 'resize.media-modal-columns';
    public id =  _.uniqueId("__attachments-view-");
    public columns;

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        $(window).off(this.resizeEvent ).on(this.resizeEvent, _.debounce(this.setColumns.bind(this), 50));
    }

    componentWillUnmount() {
        $(window).off(this.resizeEvent);
    }

    renderAttachment(attachment) {
        return <Attachment {...attachment} key={attachment.id} />
    }

    render() {
        return (
            <ul id={this.id} ref="el">
                {this.props.attachments.map((attachment) => {
                    return this.renderAttachment(attachment);
                })}
            </ul>
        );
    }

    setColumns() {
        let prev = this.columns,
            $el = $(this.refs['el']),
            width = $el.width();

        if (width) {
            this.columns = Math.min( Math.round(width / this.props.idealColumnWidth), 12) || 1;
            if (! prev || prev !== this.columns) {
                $el.closest('.media-frame-content').attr('data-columns', this.columns );
            }
        }
    }
}

export class Selection extends Attachments {
    renderAttachment(attachment) {
        return <Attachment {...attachment} key={attachment.id} className="selection" />
    }
}

(Attachments as React.ComponentClass<AttachmentsProps>).defaultProps = {
    refreshSensitivity: 200,
    refreshThreshold: 3,
    sortable: false,
    resize: true,
    idealColumnWidth: $(window).width() < 640 ? 135 : 150,
    attachments: [],
};
